﻿{extend name="public:base" /}

{block name="content"}
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox ">
                <div class="ibox-title">
                    <a href="{:url('doArticle')}" class="btn btn-primary btn-lg">新增</a>
                    <button type="button" class="btn btn-primary btn-lg sort-btn" data-toggle="modal" data-target="#myModal">排序</button>

                    <div class="ibox-tools">
                        <a class="collapse-link">
                            <i class="iconfont icon-chevron-up"></i>
                        </a>
                    </div>
                </div>

                <div class="ibox-content">
                    <div class="row search-form">
                        <div class="col-sm-2 m-b-sm">
                            <select class="form-control" name="type" id="type">
                                <option value="0">请选择所属</option>
                                <option value="1" {:input(
                                'type' )==1 ? 'selected' : '' }>18天打卡内容</option>
                                <option value="2" {:input(
                                'type' )==2 ? 'selected' : '' }>18天打卡结束内容</option>
                                <option value="3" {:input(
                                'type' )==3 ? 'selected' : '' }>软文内容</option>
                            </select>
                        </div>

                        <div class="col-sm-2 m-b-sm">
                            <div class="input-group">
                                <button type="button" class="btn btn-primary btn-lg screen-btn">搜索</button>
                            </div>
                        </div>
                    </div>

                    <div class="hr-line-solid"></div>
                    <h3>文章数量：{$count}</h3>
                    <div class="hr-line-solid"></div>

                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                            <tr>
                                <th>ID</th>
                                <th>标题</th>
                                <th>所属</th>
                                <th>打卡天数</th>
                                <th>类型</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            {volist name="page_list" id="vo"}
                            <tr>
                                <td>{$vo.id}</td>
                                <td>{$vo.title}</td>
                                <td>{$vo.type_desc}</td>
                                <td>{$vo.day ? $vo.day : ''}</td>
                                <td>{$vo.show_type_desc}</td>
                                <td>{$vo.create_time|timeFormat}</td>
                                <td class="project-actions">
                                    <a href="{:url('doArticle', ['id' => $vo.id])}" class="btn btn-white btn-sm"><i class="iconfont icon-edit"></i> 编辑
                                    </a>
                                    {if $vo.type == 3}
                                    <a onclick="setId('{$vo.id}')" class="btn btn-white btn-sm" data-toggle="modal" data-target="#spread"><i class="iconfont icon-change"></i> 软文推广
                                    </a>
                                    {/if}
                                    <a href="{:url('delArticle', ['id' => $vo.id])}" class="btn btn-white btn-sm ajax-del"><i class="iconfont icon-trash"></i> 删除
                                    </a>
                                </td>
                            </tr>
                            {/volist}
                            </tbody>
                        </table>
                        {if !empty($page_list)}{$page_list->render()}{/if}
                    </div>

                </div>
            </div>
        </div>
    </div>

    <div class="modal inmodal" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content animated flipInY">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title">排序</h4>
                </div>
                <div class="modal-body">
                    <div id="list">
                        {volist name="list" id="vo"}
                        <div data-id="{$vo.id}">{$vo.title}</div>
                        {/volist}
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="saveSort()">更新排序</button>
                </div>
            </div>
        </div>
    </div>

    <style>
        .main {
            display: flex;
            flex-direction: column;
        }

        .module-box {
            display: flex;
            flex-wrap: wrap;
            width: 100%;
            overflow-y: scroll;
            max-height: 250px;
        }

        .module {
            margin-top: 10px;
            display: flex;
            align-items: center;
            cursor: pointer;
        }

        .checkbox-input {
            width: 40px;
            height: 40px;
            line-height: 40px;
            border: 1px solid #e7eaec;
        }

        .checkbox-input input {
            margin: 13px;
            float: left;
        }

        .checkbox-name {
            text-align: left;
            height: 40px;
            line-height: 40px;
            border: 1px solid #e7eaec;
            border-left: 0;
            padding: 0 13px;
            margin-right: 10px;
        }
    </style>
    <div class="modal inmodal" id="spread" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" style="max-width: 700px;">
            <div class="modal-content animated flipInY">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title">软文推广</h4>
                </div>
                <div class="modal-body">
                    <div class="main">
                        <!-- 搜索框 -->
                        <div class="search-box mb-3">
                            <div class="input-group">
                                <input type="text" id="user_search" class="form-control" placeholder="搜索客户名称">
                                <span class="input-group-btn">
                                    <button class="btn btn-primary" type="button" id="search_btn" style="margin-left: 10px">搜索</button>
                                </span>
                            </div>
                        </div>
                        <!-- 搜索结果统计 -->
                        <div class="search-result-count mb-2" style="color: #999;">
                            共 <span id="total_count">{:count($user_list)}</span> 位用户
                        </div>
                        
                        <div class="module">
                            <div class="checkbox-input">
                                <input class="all_check" type="checkbox" value="0">
                            </div>
                            <span class="checkbox-name">全选</span>
                        </div>
                        <div class="module-box">
                            {volist name="user_list" id="vo"}
                            <div class="module" data-username="{$vo.username}">
                                <div class="checkbox-input">
                                    <input name="ids[]" class="single_check" type="checkbox" value="{$vo.id}">
                                </div>
                                <span class="checkbox-name">{$vo.username}</span>
                            </div>
                            {/volist}
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="confirmSpread()">确认</button>
                </div>
            </div>
        </div>
    </div>
</div>

{/block}


{block name="js"}
<script src="__ADMIN__/js/Sortable.js"></script>
<script>
    var type = `{:input('type')}`;
    if (type) {
        $('.sort-btn').show();
    } else {
        $('.sort-btn').hide();
    }

    (function () {
        //文字拖拽
        Sortable.create(document.getElementById('list'), {
            animation: 150,
            //onAdd,onUpdate,onRemove,onStart,onSort,onEnd
            onUpdate: function (evt) {
                var oldIndex = evt.oldIndex;
                var newIndex = evt.newIndex;
                console.log(oldIndex);
                console.log(newIndex)
            }
        });
    })();

    /**
     * 更新排序
     * */
    function saveSort() {
        var divObj = $('#list > div');
        if (divObj.length > 0) {
            var sortObj = [];
            divObj.each(function (index, val) {
                var id = val.dataset.id;

                var sortObjSingle = {};
                sortObjSingle.id = id;
                sortObjSingle.sort = index;
                sortObj[index] = sortObjSingle;
            })
            var url = "/admin/manage/sortArticle";

            $.post(url, {
                sortObj: JSON.stringify(sortObj)
            }, function (res) {
                if (res.result == 1) {
                    layer.msg(res.msg);
                    setTimeout(function () {
                        window.location.reload();
                    }, res.timer)
                } else {
                    layer.msg(res.msg)
                }
            }, 'json')
        }
    }

    /**
     * 全选和单选的交互逻辑
     */
    $(function () {
        // 搜索功能
        function searchUsers() {
            var searchText = $('#user_search').val().toLowerCase();
            var visibleCount = 0;
            var totalCount = 0;
            
            $('#spread .module[data-username]').each(function () {
                var username = $(this).data('username').toLowerCase();
                totalCount++;
                
                if (searchText === '' || username.indexOf(searchText) !== -1) {
                    $(this).show();
                    visibleCount++;
                } else {
                    $(this).hide();
                    // 保留选中状态，只隐藏不符合条件的用户
                    // 注释掉这行，避免取消选中状态
                    // $(this).find('.single_check').prop('checked', false);
                }
            });
            
            // 更新搜索结果统计
            $('#total_count').text(visibleCount);
            
            // 更新全选框状态
            updateAllCheckStatus();
        }
        
        // 搜索按钮点击事件
        $('#search_btn').on('click', function(e) {
            // 阻止事件冒泡和默认行为，确保不会触发确认推广按钮的逻辑
            e.preventDefault();
            e.stopPropagation();
            searchUsers();
        });
        
        // 搜索框回车事件
        $('#user_search').on('keyup', function (e) {
            if (e.key === 'Enter') {
                // 阻止事件冒泡和默认行为
                e.preventDefault();
                e.stopPropagation();
                searchUsers();
            }
        });

        // 全选框点击事件
        $('#spread .all_check').on('click', function () {
            var isChecked = $(this).prop('checked');
            // 设置所有可见的单选框的状态与全选框一致
            $('#spread .module[data-username]:visible .single_check').prop('checked', isChecked);
        });

        // 单选框点击事件
        $('#spread .single_check').on('click', function () {
            updateAllCheckStatus();
        });

        // 初始化时检查全选状态
        updateAllCheckStatus();

        // 确认推广按钮点击事件
        $('#spread .btn-primary').on('click', function () {
            // 获取所有选中的用户ID
            var selectedIds = [];
            $('#spread .single_check:checked').each(function () {
                selectedIds.push($(this).val());
            });

            // 如果没有选择用户，可以给个提示
            if (selectedIds.length === 0) {
                layer.msg('请至少选择一个用户');
                return;
            }

            // 这里可以添加推广逻辑，比如将选中的用户ID传递给后端
            // 实际的confirmSpread函数应该会处理这个逻辑
        });

        // 当模态框显示时，重新检查全选状态
        $('#spread').on('shown.bs.modal', function () {
            updateAllCheckStatus();
            // 清空搜索框
            $('#user_search').val('');
            // 显示所有用户
            $('#spread .module[data-username]').show();
            // 更新统计
            $('#total_count').text($('#spread .module[data-username]').length);
        });

        // 点击module直接操作对应的checkbox
        $('#spread .module').on('click', function (e) {
            // 如果点击的是checkbox本身，则不处理，避免重复触发
            if ($(e.target).is('input[type="checkbox"]')) {
                return;
            }

            // 找到当前module中的checkbox
            var checkbox = $(this).find('input[type="checkbox"]');

            // 切换checkbox的选中状态
            checkbox.prop('checked', !checkbox.prop('checked'));

            // 如果是点击的单选框，更新全选框状态
            if (checkbox.hasClass('single_check')) {
                updateAllCheckStatus();
            } else if (checkbox.hasClass('all_check')) {
                // 如果是点击的全选框，同步所有可见的单选框状态
                var isChecked = checkbox.prop('checked');
                $('#spread .module[data-username]:visible .single_check').prop('checked', isChecked);
            }
        });

        // 为checkbox添加阻止冒泡的事件，防止点击checkbox时触发外层module的点击事件
        $('#spread .module input[type="checkbox"]').on('click', function (e) {
            e.stopPropagation();
        });
    });

    /**
     * 更新全选框的状态
     */
    function updateAllCheckStatus() {
        var totalVisibleChecks = $('#spread .module[data-username]:visible .single_check').length;
        var checkedVisibleChecks = $('#spread .module[data-username]:visible .single_check:checked').length;

        // 如果所有可见的单选框都被选中，则选中全选框；否则取消选中
        $('#spread .all_check').prop('checked', totalVisibleChecks > 0 && totalVisibleChecks === checkedVisibleChecks);
    }

    var id = 0;

    function setId(choose_id) {
        id = choose_id;
    }

    function confirmSpread() {
        // 获取所有选中的用户ID
        var selectedIds = [];
        $('#spread .single_check:checked').each(function () {
            selectedIds.push($(this).val());
        })
        if (selectedIds.length === 0) {
            layer.msg('请选择用户');
        }

        $.post("{:url('/admin/manage/confirmSpread')}", {id, user_ids: selectedIds}, function (res) {
            if (res.result == 1) {
                layer.msg(res.msg);
                setTimeout(function () {
                    window.location.reload();
                }, res.timer)
            } else {
                layer.msg(res.msg)
            }
        }, 'json')
    }
</script>{/block}